from flask import g
from flask import request

from info.models import User, News, Category
from info.module.index import index_bp
from info import redis_store
from flask import session, current_app, render_template, jsonify
import logging

from info.utilities.common import user_login_data
from info.utilities.response_code import RET
from info import constants


@index_bp.route('/news_list')
def news_list():
    param_dict = request.args
    cid = param_dict.get('cid')
    page = param_dict.get('page', 1)
    per_page = param_dict.get('per_page', 10)

    if not cid:
        current_app.logger.error("参数错误")
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数格式错误")

    # if cid != 1:
    #     paginate_obj = News.query.filter(News.category_id == cid).order_by(News.create_time.desc()) \
    #         .paginate(page, per_page, False)
    # else:
    #     paginate_obj = News.query.order_by(News.create_time.desc()) \
    #         .paginate(page, per_page, False)

    filter_list = []
    if cid != 1:
        filter_list.append(News.category_id == cid)
    try:
        paginate_obj = News.query.filter(*filter_list).order_by(News.create_time.desc()) \
            .paginate(page, per_page, False)

        news_list = paginate_obj.items
        current_page = paginate_obj.page
        total_page = paginate_obj.pages

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻对象列表异常")

    news_dict_list = []
    for news in news_list if news_list else []:
        news_dict_list.append(news.to_dict())

    data = {
        "newsList": news_dict_list,
        "current_page": current_page,
        "total_page": total_page
    }

    return jsonify(errno=RET.OK, errmsg="新闻列表查询成功", data=data)


@index_bp.route('/')
@user_login_data
def index():
    # redis_store.set("name", "John")
    # session["name2"] = "Lily"
    # result = session.get("name2")

    # current_app.logger.debug('debug')
    # current_app.logger.info('info')
    # current_app.logger.warning('warning')
    # current_app.logger.error('error')
    # current_app.logger.critical('critical')

    # logging.debug("debug")

    # return "Hello! %s" % result



    # user_id = session.get("user_id")
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)
    #         return jsonify(errno=RET.DBERR, errmsg="查询用户对象异常")

    user = g.user

    # ****************查询新闻点击排行***********************
    try:
        news_rank_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻数据异常")

    news_dict_list = []
    # if news_rank_list:
    #     for news_obj in news_rank_list:
    #         news_dict = news_obj.to_dict()
    #         news_dict_list = news_dict_list.append(news_dict)
    for news_obj in news_rank_list if news_rank_list else []:
        news_dict = news_obj.to_dict()
        news_dict_list.append(news_dict)

    # ****************查询新闻分类数据***********************
    try:
        categories_list = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻分类异常")
    # 讲分类对象列表转换成字典列表
    categories_dict_list = []
    for categories_obj in categories_list if categories_list else []:
        categories_dict = categories_obj.to_dict()
        categories_dict_list.append(categories_dict)



    # if user:
    #     user_dict = user.to_dict()
    data = {
        "user_info": user.to_dict() if user else None,
        "news_rank_list": news_dict_list,
        "categories": categories_dict_list
    }
    return render_template("news/index.html", data=data)


@index_bp.route('/favicon.ico')
def get_favicon():

    return current_app.send_static_file("news/favicon.ico")
